/*
 * Database.cpp
 *
 *  Created on: 17-08-2011
 *      Author: cristian
 */

#include "Database.h"

Database* Database::INSTANCE = 0;

Database::Database() {

	logger = new Logger();
	pthread_mutex_init(&mutex, NULL);
	options.create_if_missing = true;
	status = leveldb::DB::Open(options, "db/testdb", &db);
	assert(status.ok());

}

leveldb::DB *Database::getDb() const {
	return db;
}

leveldb::Options Database::getOptions() const {
	return options;
}

void Database::setDb(leveldb::DB *db) {
	this->db = db;
}

leveldb::Status Database::getStatus() const {
	return status;
}

void Database::setStatus(leveldb::Status status) {
	this->status = status;
}

void Database::setOptions(leveldb::Options options) {
	this->options = options;
}

Logger *Database::getLogger() const {
	return logger;
}

void Database::setLogger(Logger *logger) {
	this->logger = logger;
}

Database::~Database() {
	delete db;
	delete logger;
}

void Database::put(std::string _key, std::string _value) {
	pthread_mutex_lock(&mutex);
	if (status.ok()) {
		status = db->Put(leveldb::WriteOptions(), _key, _value);
	} else {

	}
	pthread_mutex_unlock(&mutex);
}

std::string Database::get(std::string _key) {
	pthread_mutex_lock(&mutex);
#ifdef TRACE
	HAL_TRACE(logger, "@TODO Eliminar mutex de aca get key %s", _key.c_str());
#endif
	pthread_mutex_unlock(&mutex);
}

Database *Database::getInstance() {
	if (INSTANCE == 0) {
		INSTANCE = new Database();
	}
	return INSTANCE;
}

void Database::printAll() {

	leveldb::Iterator* it = this->db->NewIterator(leveldb::ReadOptions());
	for (it->SeekToFirst(); it->Valid(); it->Next()) {

#ifdef TRACE
		HAL_TRACE(
				logger,
				" key %s = value %s ", it->key().ToString().c_str(), it->value().ToString().c_str());
#endif

	}

	delete it;
}

